package chat.client.ui;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ChatUI extends JFrame{

	private JTextArea senderArea = null;
	private JTextArea receiverArea = null;
	private JScrollPane receiverAreaPane = null;
	private JScrollPane senderAreaPane = null;
	private JButton send = null;
	private BufferedWriter out = null;
	private String currentUser = null;
	
	public ChatUI(BufferedWriter out,String currentUser) {
		this();
		this.out = out;
		this.currentUser = currentUser;
		setTitle("Chat App <> User : " + this.currentUser);
	}
	public ChatUI() {
		receiverArea = new JTextArea(40,40);
		receiverArea.setEditable(false);
		receiverArea.setRows(20);
		receiverArea.setColumns(60);
		receiverArea.setWrapStyleWord(true);
		receiverAreaPane = new JScrollPane(receiverArea);

		senderArea = new JTextArea(10,20);
		senderArea.setRows(10);
		senderArea.setColumns(40);
		senderArea.setWrapStyleWord(true);
		senderAreaPane = new JScrollPane(senderArea);
		
		send = new JButton("Send");
		send.setSize(40, 60);
		send.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				String message = getTextToSend();
				try {
					out.write(message);
					out.write("\n");
					out.flush();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				clearText();
			}
		});
	}
	public void constructChatWindow(){
		setSize(800, 600);
		setLayout(new GridLayout(2, 1));
		
		add(receiverAreaPane);
		
		JPanel p = new JPanel();
		p.setLayout(new FlowLayout(FlowLayout.LEFT));
		p.add(senderAreaPane);
		p.add(send);
		
		add(p);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
	public void setReceiverData(String text,String toUser){
		String existingText = receiverArea.getText().trim();
		StringBuffer buffer = new StringBuffer(existingText);
		buffer.append('\n');
		buffer.append(toUser + " Sent : " + text);
		buffer.append('\n');
		receiverArea.setText(buffer.toString());
	}
	private String getTextToSend(){
		return senderArea.getText();
	}
	private void clearText(){
		senderArea.setText("");
	}
	public static void main(String[] args) {
		ChatUI window = new ChatUI();
		window.constructChatWindow();
	}
}
